import groovy.sql.Sql
import javax.swing.*
import javax.swing.table.*

class SqlPortableController {

    def model
    def view
    def sql

    void mvcGroupInit(Map args) {
        def home = new File(System.getProperty('user.home'), '.sqlportable')
        home.mkdirs()
        sql = Sql.newInstance("jdbc:derby:${home.absolutePath}/derbyDB;create=true", 'user', 'password', 'org.apache.derby.jdbc.EmbeddedDriver')
    }

    def openFile(evt) {
        if (view.fileChooser.showOpenDialog() == JFileChooser.APPROVE_OPTION) {
            model.sql = view.fileChooser.selectedFile.text
        }
    }

    def execute(evt) {
        view.editor.text.split(';\\s*').each {text ->
            view.console.append("$text\n\n")
            try {
                if (text =~ /(?i)^\s*(select|with).*/) {
                    def rows = sql.rows(text)
                    view.table.setModel(new DefaultTableModel(
                        rows.collect {it.collect {k,v -> v}}.asType(Object[][]),
                        rows[0].collect {k,v -> k}.asType(Object[])
                    ))
                    view.tab.selectedComponent = view.resultPane
                } else {
                    sql.execute(text)
                    view.tab.selectedComponent = view.consolePane
                }
                view.console.append("Success.\n\n")
            } catch (e) {
                view.console.append("ERROR: $e.message\n\n")
                view.tab.selectedComponent = view.consolePane
            }
        }
    }
}